#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define  NUMS           5//块数
#define  PER_BLOCK_SIZE (1024) //每一块的大小
#define  SIZE           (NUMS * PER_BLOCK_SIZE)

unsigned long getFileSize(FILE *fp)
{
    //1 先保存原来的大小
    fseek(fp,0,SEEK_CUR);
    int curPos = ftell(fp);

    //2 将文件光标移动到末尾
    fseek(fp,0,SEEK_END);
    //3 获取文件大小
    unsigned long fileSize = ftell(fp);
    //4 恢复原来的位置
    fseek(fp,curPos,SEEK_SET);
    //5 返回文件大小
    return fileSize;
}

int main() //1.txt 源文件---2.txt 目标文件
{
    //1、打开源文件 -只读
    FILE *srcFp = fopen("1.pdf","r");
    if(srcFp == NULL){
        perror("fopen");
        return -1;
    }
    //2、打开目标文件--只写 不存在创建 存在则清空
    FILE *destFp = fopen("2.pdf","w");
    if(destFp == NULL){
        perror("fopen");
        return -1;
    }

    unsigned long fileSize = getFileSize(srcFp);
    printf("fileSize = %lu\n",fileSize);
    int cnt=0;

    char *buf = malloc(NUMS*PER_BLOCK_SIZE);
    printf("1111\n");

    while(1)
    {
         printf("2222\n");
        //3、循环读取源文件的内容
        memset(buf,0,SIZE);
        //char buf[1024] = {0};

        int pos1 = ftell(srcFp);

        int n = fread(buf,PER_BLOCK_SIZE,NUMS,srcFp);
        if(n < NUMS)
        {
            //要么读完了
            if(feof(srcFp) != 0){
                printf("文件读取完毕\n");
                int pos2 = ftell(srcFp);
                //最后一次读取的时候，也要写入
                fwrite(buf,pos2-pos1,1,destFp);

                cnt += (pos2-pos1);

                printf("总文件:%lu,已拷贝:%d 约%.2fMB 进度%.2f%%\n",
                        fileSize,
                        cnt,
                        cnt*1.0/1024/1024,
                        cnt*1.0/fileSize * 100);

                break;
            }
            //要么出错了
            if(ferror(srcFp) != 0){
                printf("文件读取出错\n");
                break;
            }
        }
        //4、循环写入到目标文件中
        fwrite(buf,PER_BLOCK_SIZE,NUMS,destFp);

        cnt+=(PER_BLOCK_SIZE*NUMS);

        printf("总文件:%lu,已拷贝:%d 约%.2fMB 进度%.2f%%\n",
                                fileSize,
                                cnt,
                                cnt*1.0/1024/1024,
                                cnt*1.0/fileSize * 100);
    }

    //5、关闭文件
    fclose(srcFp);
    fclose(destFp);
    free(buf);
    buf = NULL;

    return 0;
}